package BitCreekTracker;

import BitCreekLib.TorrentMetaDati;

import static java.lang.Thread.sleep;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Created by Ivan Litsvinenka e Emanuele Ricci
 * Date: 29-lug-2009
 * Time: 16.17.42
 */
public class TrackerKeepAliveThread implements Runnable {

    private static final int KA_SLEEP = 4*15000;

    public void run() {
        while ( true ) {
        		
	        	System.out.println("Start new KeepAlive check: ");
	        	try {
		            for ( Map.Entry<String,TorrentMetaDati> hr: TrackerServices.tht.entrySet() ) {
		            	TorrentMetaDati tmd = hr.getValue();        	
	            		
		                System.out.println("Check per " +hr.getKey());
		                ArrayList<TrackerPeer> tpToremove  = new ArrayList<TrackerPeer>();
		                for ( TrackerPeer tp : tmd.getPeers() ) {
		                    System.out.println("[KA " + tp.getHost().toString()+" ]: " + ( tp.getLastKA() < (System.currentTimeMillis()-KA_SLEEP)));
		                    if (  tp.getLastKA() < System.currentTimeMillis()-KA_SLEEP )
		                    	tpToremove.add(tp);
		                }
		                
		                for ( TrackerPeer tp : tpToremove )
		                	tmd.removePeer(tp);
		                
		                if ( tmd.getPeers().size() < 1 ) {
		                    System.out.println("Removing torrent: " + tmd.getMetaInfo().getName()+ " , no more peers.");
		                    TrackerServices.tht.remove(hr.getKey());
		                }
	            		
		                
		
		            } 
	        	} 
	        	catch ( ConcurrentModificationException e) {} 
	        	catch ( NoSuchElementException e) {}
	            
	            if ( TrackerServices.tht.size() < 1 ) 
	            	System.out.print("No more torrents in the Hash Table.");
	            
	            
	            try {
	                sleep(KA_SLEEP);
	            } catch ( InterruptedException e ) {}

        }

    }

}
